#! /usr/bin/env node

const fs = require('fs');
var pinyin = require("pinyin");
var path = require("path");

class ExtraLang{
  constructor(){
    this.value = "";
  }
  set(langFile, key, value){
    let addStr = '    "' + key + "\": " + '"' + value + '", \r';
    // lang文件中不存在才能插入内容
    if (langFile.indexOf(addStr) === -1 && this.value.indexOf(addStr) === -1) {
      this.value += addStr;
    }
  }
  get(){
    return this.value
  }
}

let firstUpper = (str) => {
  return str.charAt(0).toUpperCase() + str.slice(1)
}
let getLangKey = (str) => {
  return pinyin(str, { style: pinyin.STYLE_NORMAL }).map((i, index) => {
    let word = i[0];
    word = word.replace(/[\(\)]+/g, "");
    // pingyin库会返回标点符号，这里去除，保证生成驼峰拼音
    if (!/[a-zA-Z]+/.test(word)) { return }
    // 第二个字开始首字母大写
    if (index !== 0) { return firstUpper(word) }
    return word
  }).join("");
}
let replaceFile = (vuePath, langPath) => {
  console.log(' 读取文件 >>>', vuePath);
  let vueFile = fs.readFileSync(vuePath, 'utf8',);
  let langFile = fs.readFileSync(langPath || 'zh.js', 'utf8',);
  let newVueFile = vueFile;
  let newLangStr = new ExtraLang();
  // ------------------------template区域
  // 1 替换 title="xxxx"格式内容
  let reg = /([\w-]+)=['"]([\u4E00-\u9FA5][ ]*[\u4E00-\u9FA5\w\(\)]+)['"]/;
  while (newVueFile.match(reg) && newVueFile.match(reg)[0]) {
    // title="xxxx"
    let attrWord = newVueFile.match(reg)[0];
    // title
    let attrTitle = newVueFile.match(reg)[1];
    // xxxx
    let zhWord = newVueFile.match(reg)[2];
    let langKey = getLangKey(zhWord);

    newVueFile = newVueFile.replace(attrWord, `:${attrTitle}="$t('lang.${langKey}')"`);
    newLangStr.set(langFile, langKey, zhWord);
  }
  // 3 替换 >保存< 格式
  let reg3 = />([\u4E00-\u9FA5]+[\u4E00-\u9FA5\w\(\)!-]+)</;
  while (newVueFile.match(reg3) && newVueFile.match(reg3)[0]) {
    let allWord = newVueFile.match(reg3)[0];
    let content = newVueFile.match(reg3)[1];
    let langKey = getLangKey(content);
    newVueFile = newVueFile.replace(allWord, `>{{ $t('lang.${langKey}') }}<`);
    newLangStr.set(langFile, langKey, content);
  }
  // ---------------------script区域
  // 2 替换js区域
  let reg2 = /['"]([\u4E00-\u9FA5]+[\u4E00-\u9FA5\w\(\)\!\-\? \。\？\，\,\【\】\！]+)['"]/;
  while (newVueFile.match(reg2) && newVueFile.match(reg2)[0]) {
    let allWord = newVueFile.match(reg2)[0];
    let content = newVueFile.match(reg2)[1];
    let langKey = getLangKey(content);
    newVueFile = newVueFile.replace(allWord, `this.$t('lang.${langKey}')`);
    newLangStr.set(langFile, langKey, content);
  }

  // 输出vue文件
  fs.writeFileSync(vuePath, newVueFile);
  console.log(' 生成vue 成功 >>>',);
  // 输出lang.js文件
  if(newLangStr.get()){langFile = langFile.replace("lang: {", "lang: { \r" + newLangStr.get());}
  fs.writeFileSync(langPath, langFile);
  console.log(' 生成zh.js 成功 >>>',);
}
function deepGetFile(dir) {
  let backList = []
  let list = fs.readdirSync(dir)

  for (let index in list) {
    let item = path.resolve(dir, list[index])
    if (fs.statSync(item).isDirectory()) {
      backList = backList.concat(deepGetFile(item))
    } else {
      backList.push(item)
    }
  }
  return backList
}

// 获取参数
let langPath = process.argv[2] || "zh.js";
let filePath = process.argv[3];
// 参数逻辑处理
try {
  if (!filePath) {
    throw new Error('请传入参数 >>> c_lang langPath filePath')
  }
} catch (e) {
  console.error(e.message);
  throw new Error(e.message)
}

// 区分路径是文件还是文件夹
if (filePath.indexOf(".vue") !== -1) {
  replaceFile(filePath, langPath);
} else {
  const files = deepGetFile(filePath);
  files.forEach(name => {
    if (name.indexOf(".vue") !== -1) {
      let vueP = path.resolve(filePath, name);
      replaceFile(vueP, langPath)
    }
  })
}




